import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from './storage'
import { Toast } from 'vant'

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: () => import('../views/Login.vue') },
  { path: '/register', component: () => import('../views/Register.vue') },
  { path: '/article/:id', component: () => import('../views/Detail.vue') },
  {
    path: '/',
    component: () => import('../views/Layout.vue'),
    redirect: '/article',
    children: [
      { path: 'article', component: () => import('../views/Article.vue') },
      { path: 'collect', component: () => import('../views/Collect.vue') },
      { path: 'like', component: () => import('../views/Like.vue') },
      { path: 'user', component: () => import('../views/User.vue') }
    ]
  }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login', '/register']

router.beforeEach((to, from, next) => {
  if (getToken()) {
    next()
  } else if (whiteList.includes(to.path)) {
    next()
  } else {
    Toast('请先登录')
    next('/login')
  }
})

export default router
